package com.yjps.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yjps.common.authc.PasswordHelper;
import com.yjps.common.exception.DocumentException;
import com.yjps.common.message.Message;
import com.yjps.system.model.Role;
import com.yjps.system.model.User;
import com.yjps.system.service.RoleService;
import com.yjps.system.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * 控制登陆 登出 获得个人信息显示控制类
 * Created by jessy on 2015/8/18.
 */
@Controller
public class LoginController {
    Logger log = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;

    /**
     * 请求登陆面
     * @return
     */
    @RequestMapping(value = "/system/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    /**
     * 登录验证
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "/system/login",method = RequestMethod.POST)
    public String login(@RequestParam(value = "username",required = true)String username,
                        @RequestParam(value = "password",required = true)String password,HttpServletRequest request){
        try {
            Subject subject  = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            subject.login(usernamePasswordToken);
            User u = userService.findUserByName(username);
            request.getSession().setAttribute("loginUser",u);
        } catch (UnknownAccountException uae) {
            request.setAttribute("message","用户不存在");
            return "redirect:/system/login";
        } catch (IncorrectCredentialsException ice) {
            request.setAttribute("message","用户名或密码错误");
            return "redirect:/system/login";
        } catch (LockedAccountException lae) {
            request.setAttribute("message","用户名或密码错误");

            return "redirect:/system/login";
        } catch (AuthenticationException ae) {
            request.setAttribute("message","用户名或密码错误");

            return "redirect:/system/login";
        }

        return "redirect:/system/person/home";
    }

    /**
     * 获得当前登陆用户的个人信息
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/system/person/personInfo",method = RequestMethod.GET)
    public String getPersonInfo(HttpServletRequest request,Model model){
        User user = (User) request.getSession().getAttribute("loginUser");
        System.out.println("1--------------- " + request.getSession().getAttribute("loginUser"));
        System.out.println("...... >>>>> " + user);
        user = userService.findUser(user.getId());
        System.out.println("pass ..... " + user.getPassword());
        Set<Role> roles = user.getRoles();
        StringBuilder sb = new StringBuilder();
        if(roles != null && roles.size()>0) {
            System.out.println("role.....1");
            for (Role r : roles) {
                if (r != null) {
                    sb.append(r.getRolename() + ",");
                }
            }
            if (sb.length() > 0)
                sb.substring(0, sb.length() - 1);
            if (!StringUtils.isEmpty(sb.toString())) {
                user.setViewRoleName(sb.toString());
            } else {
                user.setViewRoleName(null);
            }
        }
        model.addAttribute("user",user);
        return "/system/person/personInfo";
    }

    /**
     * 获得用户json数据
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/system/person/getUser",method = RequestMethod.GET)
    public String getUser(@RequestParam(value = "id",required = true)String id){
        User u = userService.findUser(Integer.parseInt(id));
        Set<Role> roles = u.getRoles();
        List<Role> roleList = roleService.roleList();
        u.setAllRoles(roleList);
        String jsonString = JSON.toJSONString(u);
        System.out.println("json  = " + jsonString);
        return jsonString;
    }

    /**
     * 修改个人信息
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/system/person/edit",method = RequestMethod.POST)
    public String editUser(User user,Model model){
        userService.updateUser(user);
        model.addAttribute("message", "修改信息成功！");
        return "redirect:/system/person/personInfo";
    }

    /**
     * 编辑密码
     * @param id
     * @param password
     * @param rePassword
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/system/person/password/edit",method = RequestMethod.POST)
    public String editPassword(@RequestParam(value = "id",required = true)String id,
                               @RequestParam(value = "password",required = true)String password,
                               @RequestParam(value = "rePassword",required = true)String rePassword,
                               Model model,HttpServletRequest request){
        if(!password.equals(rePassword)) {
            System.out.println("password is no yi yang ");
            model.addAttribute("message","密码不一致");
            return "redirect:/system/person/personInfo";
        }
        User user = userService.findUser(Integer.parseInt(id));
        System.out.println("user >>>>> " + user);
        System.out.println("user " + user.getId() + " username = " + user.getUsername());
        String passwordAfter = PasswordHelper.generatePassword(user.getUsername(), password);
        System.out.println("after password = " + passwordAfter);
        user.setPassword(passwordAfter);
        userService.updateUser(user);
        model.addAttribute("message","密码修改成功！");
        return "redirect:/system/person/personInfo";
    }

    @RequestMapping(value = "/system/person/home",method = RequestMethod.GET)
    public String home(){
        return "home";
    }
    @RequestMapping(value = "/system/person/logout",method = RequestMethod.GET)
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("loginUser");
        return "redirect:/system/login";
    }

    @RequestMapping(value = "/system/person/exception",method = RequestMethod.GET)
    public String exception(HttpServletRequest request){
        System.out.println("exception  ");
        return "redirect:/system/exception";
    }


    /**
     * 公司形象前台获得当前登陆用户的个人信息
     * @param request
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/company/person/personInfo.do",method = RequestMethod.GET)
    public String getPersonInfoFront(HttpServletRequest request,Model model){
        Message message = null;
        try {
            User user = (User) request.getSession().getAttribute("loginUser");
            user = userService.findUser(user.getId());
            Set<Role> roles = user.getRoles();
            StringBuilder sb = new StringBuilder();
            if (roles != null && roles.size() > 0) {
                System.out.println("role.....1");
                for (Role r : roles) {
                    if (r != null) {
                        sb.append(r.getRolename() + ",");
                    }
                }
                if (sb.length() > 0)
                    sb.substring(0, sb.length() - 1);
                if (!StringUtils.isEmpty(sb.toString())) {
                    user.setViewRoleName(sb.toString());
                } else {
                    user.setViewRoleName(null);
                }
            }
            message = new Message(true,"获取信息成功",user);
        }catch (Exception e){
            message = new Message(false,"获取信息失败");
        }
        return message.toJson();
    }

    /**
     * 公司形象前台 编辑密码
     * @param id
     * @param password
     * @param rePassword
     * @param
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/company/person/password/edit.do",method = RequestMethod.POST)
    public String editPasswordFront(@RequestParam(value = "id",required = true)String id,
                                    @RequestParam(value = "password",required = true)String password,
                                    @RequestParam(value = "rePassword",required = true)String rePassword,
                                    HttpServletRequest request){
        Message message = null;
        try {
            if (!password.equals(rePassword)) {
                message = new Message(false,"密码不一致");
                return message.toJson();
            }
            User user = (User) request.getSession().getAttribute("loginUser");
            user = userService.findUser(user.getId());
            System.out.println("user " + user.getId() + " username = " + user.getUsername());
            user.setPassword(PasswordHelper.generatePassword(user.getUsername(), password));
            userService.updateUser(user);
            message = new Message(true,"密码修改成功",user);
        }catch (Exception e){
            message = new Message(false,"密码修改失败");
        }
        return message.toJson();
    }

    /**
     * 公司前台更新用户信息
     * @param json
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/company/person/edit.do",method = RequestMethod.POST)
    public String editUserFront(@RequestParam(value = "json",required = true)String json){
        Message message = null;
        try {
            JSONObject jsonObject = JSON.parseObject(json);
            String id = jsonObject.get("id").toString();
            User user = userService.findUser(Integer.parseInt(id));

            user.setUsername((String) jsonObject.get("username"));
            String mobile = jsonObject.get("mobile").toString();
            user.setMobile(mobile);
            String email = jsonObject.get("email").toString();
            user.setEmail(email);
            String realName = jsonObject.get("realName").toString();

            user.setRealName(realName);
            userService.updateUser(user);
            message = new Message(true,"修改信息成功",user);
        }catch (Exception e){
            message = new Message(false,"信息修改失败");
        }
        return message.toJson();
    }
}
